import Ajax from '../../utils/request.js'
import Wxml2Canvas from '../../canvasJS/index';

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    shareImageUrl: '',
    imgUrls: [],
    currentSwiper: 0,
    autoplay: true,
    isHideScollBool: false,
    visitList: [],
    appointmentList: [],
    activeItem: {},
    showInstructionsBool: false,
    appointmentBool: false,
    scrollBool: false,
    appointmentStep: 1, // 预约步骤
    elderName: '',
    roomName: '',
    name1: '',
    name2: '',
    errorTip: '老人姓名不存在，请检查后重新输入。',
    shareModel: false,
    activeAppintmentItem: {},
    showErrorTip: false, // 是否展示错误信息
    userInfoData: {},
    showReturnBtn: false,
    orgInfo: {}, // 机构信息
    sharePostersBool: false,
    width: 506,
    height: 665,
    elderNameFocus: false,
    roomNameFocus: false,
    name1Focus: false,
    name2Focus: false,
  },
  onLoad: function(options) {
    this.getVisitConfEvent();
    this.getUserInfoEvent();
    this.getBannerEvent();
    this.getOrgEvent();
    // this.getSystemInfo();
  },
  focusEvent(e) {
    let item = e.currentTarget.dataset['item'];
    this.setData({
      [item]: true
    })
  },
  getSystemInfo() {
    wx.getSystemInfo({
      success: (res) => {
        console.log(res);
        this.setData({
          width: res.screenWidth,
          height: res.screenHeight
        });
      }
    })
  },
  onShareAppMessage() {
    let _this = this;
    _this.setData({
      shareModel: false
    })
  },
  bindCloseShareEvent() {
    let _bool = this.data.sharePostersBool
    this.setData({
      shareModel: false,
      sharePostersBool: !_bool
    })
  },
  // 获取轮播图地址
  async getBannerEvent() {
    try {
      let res = await Ajax.get('/wxa/appImage/getList');
      let _list = res.result;
      let shareImageUrl = '../../images/share-poster.png';
      if (_list.length) {
        shareImageUrl = _list[0].imageUrl
      }
      this.setData({
        imgUrls: _list ? _list : [],
        shareImageUrl: shareImageUrl
      })
    } catch (error) {
      console.log(error)
    }
  },
  // 获取机构信息
  async getOrgEvent() {
    try {
      let res = await Ajax.get('/wxa/org/getOrg');
      let _data = res.result || {}
      this.setData({
        orgInfo: _data
      })
    } catch (error) {
      console.log(error)
    }
  },
  goLocationEvent() {
    // wx.redirectTo({
    //   url: '/pages/siteMap/index'
    // })
    let {
      longitude,
      latitude,
      orgName
    } = this.data.orgInfo
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: orgName,
      scale: 20
    });
  },
  getVisitNum(list) {
    let sumNum = 0;
    for (let item of list) {
      sumNum = sumNum + item.appointNum
    }
    return sumNum
  },
  // 获取预约探视的配置
  async getVisitConfEvent() {
    try {
      let res = await Ajax.get('/wxa/visit/getVisitConf');
      let data = res.result && res.result.map ? res.result.map : [];
      for (let item of data) {
        item.appointNum = this.getVisitNum(item.list)
      }
      this.setData({
        visitList: data
      })
    } catch (error) {
      console.log(error)
    }
  },
  // 点击探视须知
  bindInstructionsEvent(event) {
    let query = event.currentTarget.dataset['index'];
    this.setData({
      showInstructionsBool: query == 'true',
      isHideScollBool: query == 'true',
    })
  },
  //滑动事件监听
  swiperChange: function(event) {
    this.setData({
      currentSwiper: event.detail.current
    });
  },
  //banner点击事件
  tapBanner: function(event) {
    var indexUrl = this.data.imgUrls[this.data.currentSwiper];
    var url = event.currentTarget.dataset.indexurl;
    console.log(url);
  },
  // 预约
  bindVisitEvent(event) {
    let item = event.currentTarget.dataset['item'];
    this.setData({
      appointmentBool: true,
      isHideScollBool: true,
      activeItem: item,
      appointmentStep: 1,
      appointmentList: item.list,
      activeAppintmentItem: {}
    })
  },
  bindAppointmentEvent(event) {
    let item = event.currentTarget.dataset['item'];
    this.setData({
      activeItem: item,
      appointmentList: item.list,
      activeAppintmentItem: {}
    })
  },
  bindAppointmentItemEvent(event) {
    let item = event.currentTarget.dataset['item'];
    if (item.appointNum < 1) {
      return false
    }
    this.setData({
      activeAppintmentItem: item,
    })
  },
  bindNextStep(event) {
    if (!this.data.activeAppintmentItem.id) {
      return false
    }
    this.setData({
      appointmentStep: 2
    })
  },

  bindHideVisitEvent() {
    this.setData({
      appointmentBool: false,
      isHideScollBool: false
    })
  },
  //input输入框
  bindKeyInput(e) {
    let item = e.currentTarget.dataset['input'];
    this.setData({
      [item]: e.detail.value,
    });
  },
  async formSubmit(e) {
    //如果未实名认证
    let _this = this;
    wx.getSetting({
      success: res => {
        console.log(res);
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          _this.submitEvent(e)
        } else {
          wx.redirectTo({
            url: '/pages/authorization/authorization'
          });
        }
      }
    })
    return false;
    if (!app.globalData.isRealNameBool) {
      wx.showToast({
        title: '请先实名认证',
        icon: 'none',
        duration: 1500,
      })
      let timer = setTimeout(() => {
        clearTimeout(timer)
        wx.redirectTo({
          url: '/pages/realname/index'
        })
      }, 1500)
    }
  },
  async submitEvent(e) {
    let formData = e.detail.value;
    let {
      activeAppintmentItem,
      activeItem
    } = this.data;
    let appointUser = formData.name2 ? `${formData.name1},${formData.name2}` : `${formData.name1}`
    let params = {
      elderName: formData.elderName,
      roomName: formData.roomName,
      visitTime: activeItem.visitTime,
      appointUser,
      startTime: activeAppintmentItem.startTime,
      endTime: activeAppintmentItem.endTime,
    }
    try {
      let res = await Ajax.post('/wxa/visit/add', params);
      console.log(res.code)
      if (res.code != 1) {
        wx.showToast({
          title: res.errorMsg,
          icon: 'none',
          duration: 2000
        })
        return false;
      }
      wx.redirectTo({
        url: '/pages/appointmentResults/index?id=' + res.result.appointCode
      })
    } catch (error) {
      console.log(error)
    }
  },
  // 点击分享图标
  bindShareEvent(event) {
    let _bool = this.data.shareModel
    this.setData({
      shareModel: !_bool,
    })
  },
  // 获取用户信息
  async getUserInfoEvent() {
    try {
      let res = await Ajax.get('/wxa/members/getUserInfo');
      if (res.code != 1) {
        wx.showToast({
          title: res.errorMsg,
          icon: 'none',
          duration: 2000
        })
        return false;
      }
      this.setData({
        userInfoData: res.result || {}
      })
      let _status = res.result.status
      app.globalData.isRealNameBool = _status
      app.globalData.userData = res.result
    } catch (error) {
      console.log(error)
    }
  },
  drawImage() {
    wx.showLoading({
      title: '海报生成中...',
    })
    let _this = this;
    var drawimg = new Wxml2Canvas({
      width: _this.data.width,
      height: _this.data.height,
      element: 'canvas1',
      background: '#000000',
      progress(percent) {},
      finish(url) {
        wx.hideLoading();
        wx.saveImageToPhotosAlbum({
          filePath: url
        });
        wx.showToast({
          title: '保存成功',
        })
        _this.setData({
          sharePostersBool: false
        })
      },
      error(res) {
        console.log(ers)
      }
    });

    let data = {
      list: [{ //绘制矩形
          type: 'rect',
          x: 0,
          y: 0,
          style: {
            width: 506,
            height: 665,
            fill: '#fff'
          }
        },
        { //根据wxml绘制,
          type: 'wxml',
          class: '.share__canvas1 .draw_canvas',
          limit: '.share__canvas1',
          x: 0,
          y: 0
        }
      ]
    }
    drawimg.draw(data);
  },
})